// 子仓库
import { getCartList, changeCount, delSelect } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    // 提供一个设置cartlist的方法
    setCartList (state, newlist) {
      state.cartList = newlist
    },
    // 让对应的id取反
    toggleCheck (state, goodsId) {
      state.cartList.forEach(item => {
        if (item.goods_id === goodsId) {
          item.isChecked = !item.isChecked
        }
      })
    },
    changeCount (state, obj) {
      const { goodsId, goodsNum } = obj
      state.cartList.forEach(item => {
        if (item.goods_id === goodsId) {
          item.goods_num = goodsNum
        }
      })
    },
    // 点击全选
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    }

  },
  actions: {
    async getCartAction (context) {
      const { data } = await getCartList()
      // 后台返回数据不全，不包含复选框选中状态，为了实现功能，需要手动维护数据需要添加一个isChecked 属性
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsNum, goodsId, goodsSkuId } = obj
      context.commit('changeCount', { goodsId, goodsNum })
      await changeCount(goodsId, goodsNum, goodsSkuId)
      // 先本地修改在提交后台
      // console.log(res)
    },
    // 删除购物车
    async delSelect (context, getters) {
      const selCartList = context.getters.selCartList
      const cartIde = selCartList.map(item => item.id)
      // console.log(cartIde)
      await delSelect(cartIde)
      Toast('删除成功')
      // 重新拉取渲染
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 求所有商品的总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },

    // 选中的商品项
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中的总数
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的总价
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods.goods_price_min * item.goods_num, 0).toFixed(2)
    },
    // 判断是否全选
    isAllCheck (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
